package top.lww0511.extra.utils;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

/**
 * @author lww
 */
public class MpExtraUtil {

    @SneakyThrows
    public static Object getValue(Object o, String name) {
        Class<?> aClass = o.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getName().equals(name)) {
                return field.get(o);
            }
        }
        throw new IllegalArgumentException("未查询到名称为：" + name + " 的字段");
    }

    /**
     * 驼峰转下划线
     */
    public static String humpToUnderline(String str) {
        String regex = "([A-Z])";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group();
            str = str.replaceAll(target, "_" + target.toLowerCase());
        }
        return str;
    }

    public static String first2Lower(String str) {
        if (StringUtils.isEmpty(str)) {
            return "";
        } else {
            String s = str.substring(0, 1);
            return s.toLowerCase() + str.substring(1);
        }
    }

    /**
     * 下划线转驼峰
     */
    public static String underlineToHump(String str) {
        String regex = "_(.)";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group(1);
            str = str.replaceAll("_" + target, target.toUpperCase());
        }
        return str;
    }
}
